package org.msfj.generator;

import org.apache.ibatis.io.Resources;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Properties;

public class CommonPageParser {
    private static VelocityEngine ve;
    private static final String CONTENT_ENCODING = "UTF-8";
    static {
        try {
            URL resourceURL = Resources.getResourceURL("template");
            String path = resourceURL.getPath();
            ve = new VelocityEngine();
            Properties props = new Properties();
            props.put("file.resource.loader.path", path);
            ve.init(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void WriterPage(VelocityContext context, String templateName, String fileDirPath, String targetFile) {
        try {
            File file = new File(fileDirPath + targetFile);
            if (!file.exists()) {
                new File(file.getParent()).mkdirs();
            }
            Template template = ve.getTemplate(templateName,CONTENT_ENCODING);
            FileOutputStream fos = new FileOutputStream(file);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, CONTENT_ENCODING));
            template.merge(context, writer);
            writer.flush();
            writer.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}